# -*- coding: UTF-8 -*-
# Author: Damon(wuud1)
# CreateDate:
# Message: 集合了自己写的所有成熟通用的函数

import time

def loop(file_name='./error.log'):
    '''无限循环装饰器,程序报错会重启程序,爬虫程序需配合断点
    续爬功能使用,否则可能会陷入死循环'''
    def _while(func):
        def tool(*args, **kwargs):
            while True:
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    with open(file_name, 'a') as f:
                        try:
                            time_str = time.strftime('%Y-%m-%d,%H:%M:%S',time.localtime())
                        except:
                            import time
                            time_str = time.strftime('%Y-%m-%d,%H:%M:%S',time.localtime())
                        f.write(time_str+'\n')
                        f.write(e.message+'\n')
                        f.write('\n')
        return tool
    return _while

def runtime(func):
    '''查看运行时间装饰器'''
    def tool(*args, **kwargs):
        time1 = time.time()
        res = func(*args, **kwargs)
        time2 = time.time()
        # a = float('%.2f' % (time2-time1))
        a = round((time2-time1),2)
        h = int(a // 3600)
        m = int((a-h*3600) // 60)
        s = float('%.2f'%(a % 60))
        print '总用时: {}小时{}分{}秒'.format(h, m, s)
        return res
    return tool

def strip_other(str, remove_list):
    '''去除str左右两侧remove_list中包含的字符'''
    remove_str = ''.join(remove_list)
    while True:
        res = False
        if str[:1] in remove_str:
            str = str[1:]
            res = True
        if str[-1:] in remove_str:
            str = str[:-1]
            res = True
        if not res:
            break
    return str

def remove_ch(str):
    '''去除字符串中的中文'''
    def is_Chinese(word):
        for ch in word:
            if '\u4e00' <= ch <= '\u9fff':
                return True
        return False
    res = ''
    for i in str:
        _is = is_Chinese(i)
        if not _is:
            res = res + i
    return res

def myfunc(lists):
    # 传入若干个列表, 输出列表所有元素的排列组合,同一个列表内的元素不进行排列组合
    # list all possible composition from many list, each item is a tuple.
    # Here lists is [list1, list2, list3], return a list of [(item1,item2,item3),...]
    # len of result list and result list.
    total = reduce(lambda x, y: x * y, map(len, lists))
    retList = []
    # every item of result list.
    for i in range(0, total):
        step = total
        tempItem = []
        for l in lists:
            step /= len(l)
            tempItem.append(l[int(i / step % len(l))])
        retList.append('.'.join(tempItem))
    return retList
